﻿using DeviceController.NetCoreServer.Services;
using NetServer;
using System;
using System.Collections.Concurrent;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Timers;
using System.Windows;
using TouchSocket.Core;

namespace DeviceController.Server
{
    class SessionInfo
    {
        public string? Ip { get; set; }

        public int Port { get; set; }
    }

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private Timer _testTimer;

        private DeviceControllerServer? _server;

        private ConcurrentDictionary<TcpSession, SessionInfo> SessionInfos;

        public MainWindow()
        {
            _testTimer = new Timer(2000);
            _testTimer.Elapsed += OnTestTimerElapsed;
            SessionInfos = new ConcurrentDictionary<TcpSession, SessionInfo>();
            InitializeComponent();
        }

        private void OnTestTimerElapsed(object? sender, ElapsedEventArgs e)
        {
            if (_server?.IsStarted == true)
            {
                var data = CreateTestData();
                var jsonData = JsonSerializer.Serialize(data);
                _server.Multicast(Encoding.UTF8.GetBytes(jsonData));

                this.Dispatcher.Invoke(new Action(() =>
                {
                    TipMessageTextBox.Text += "发送测试数据成功！" + "\n";
                }));
            }
            else
            {
                this.Dispatcher.Invoke(new Action(() =>
                {
                    TipMessageTextBox.Text += "未打开服务器！" + "\n";
                }));
            }
        }

        private void OnTestClick(object sender, RoutedEventArgs e)
        {
            _server?.Multicast("Hello World!");
        }

        private void OnOpenServerClick(object sender, RoutedEventArgs e)
        {
            if (_server?.IsStarted == true)
            {
                TipMessageTextBox.Text += "服务器已启动!" + "\n";
                return;
            }

            try
            {
                _server ??= new DeviceControllerServer(IPAddress.Parse(IPTextBox.Text), int.Parse(PortTextBox.Text));
                _server.Connected += OnConnected;
                _server.Disconnected += OnDisconnected;
                _server.Start();
                TipMessageTextBox.Text += "服务器启动成功！" + "\n";
            }
            catch (Exception)
            {
                TipMessageTextBox.Text += "服务器启动失败！" + "\n";
            }

        }

        private void OnConnected(object? sender, TcpSession session)
        {
            SessionInfos.TryAdd(session, new SessionInfo() { Ip = session.Socket.RemoteEndPoint.GetIP(), Port = session.Socket.RemoteEndPoint.GetPort() });

            Application.Current.Dispatcher.Invoke(() =>
            {
                TipMessageTextBox.Text += $"{session.Socket.RemoteEndPoint.GetIP()}:{session.Socket.RemoteEndPoint.GetPort()} 连接到服务器！" + "\n";
            });

            if (session is DeviceControllerSession deviceControllerSession)
            {
                deviceControllerSession.Received -= OnDeviceControllerSessionReceived;
                deviceControllerSession.Received += OnDeviceControllerSessionReceived;
            }
        }

        private void OnDeviceControllerSessionReceived(object? sender, ReceivedEventArgs e)
        {
            var value = Encoding.UTF8.GetString(e.ReceivedData);
            this.Dispatcher.Invoke(() =>
            {
                TipMessageTextBox.Text += value + "\n";
            });
        }

        private void OnDisconnected(object? sender, TcpSession session)
        {
            var info = SessionInfos[session];
            Application.Current.Dispatcher.Invoke(() =>
            {
                TipMessageTextBox.Text += $"{info.Ip}:{info.Port} 客户端断开！" + "\n";
            });
            SessionInfos.TryRemove(session, out _);
        }

        private void OnCloseServerClick(object sender, RoutedEventArgs e)
        {
            if (_server is null || !_server.IsStarted)
            {
                TipMessageTextBox.Text += "服务器未启动！" + "\n";
                return;
            }

            _server.DisconnectAll();
            _server.Stop();
            TipMessageTextBox.Text += "服务器已关闭！" + "\n";
        }

        private void OnAutoTestClick(object sender, RoutedEventArgs e)
        {
            if (_testTimer.Enabled)
            {
                TipMessageTextBox.Text += "自动测试已打开！" + "\n";
                return;
            }

            _testTimer.Start();
            TipMessageTextBox.Text += "自动测试打开成功！" + "\n";
        }

        private void OnCloseTestClick(object sender, RoutedEventArgs e)
        {
            if (_testTimer.Enabled)
            {
                TipMessageTextBox.Text += "自动测试已关闭！" + "\n";
            }

            _testTimer.Stop();
            TipMessageTextBox.Text += "自动测试关闭成功！" + "\n";
        }

        private PartitionPackageAM CreateTestData()
        {
            Random random = new Random();
            var data = new PartitionPackageAM();
            data.thickness = new float[1000];

            for (int i = 0; i < 1000; i++)
            {
                data.thickness[i] = random.Next(0, 1000);
            }

            return data;
        }
    }
}
